// let URL = "https://step2step.cn/mg/video/download";
let URL = "https://jsz315.xyz/ns/video/download";

// let URL = "http://49.51.69.50:3000/video/download";

// import { URL } from "./config";

console.log("inject js");

window.onload = function () {
    setTimeout(() => {
        console.log("search", location.search);
        let url = decodeURIComponent(location.search.split("=").pop());
        // document.getElementById("main_page_text").value = url;
        // localStorage.setItem("url", url)
        // alert(localStorage.getItem("url"))
        // chrome.storage.sync.set({ 'url': url }, function () {
        //     console.log('Settings saved');
        // });

        if (url) {
            chrome.runtime.sendMessage({ action: "save", url: url });
            start(url);
        }
        else {
            // url = localStorage.getItem("url")
            // chrome.storage.sync.get(['url'], function (items) {
            //     console.log('Settings retrieved', items);
            // });
            chrome.runtime.sendMessage({ action: "read" }, (e) => {
                console.log(e, "收到")
                download(e.url)
            });
            // download(url)
        }

    }, 900);
}


async function start(url) {
    console.log("start", url)
    document.title = "开始";
    await sleep(200);
    var t = document.getElementById("tweetURL");
    t.value = url;
    await sleep(1200);
    // alert(t.value);
    var btn = document.getElementById("submitBtn");
    btn.click();

    // window.open(link, "_blank");

    // history.back();
}

async function download(url) {
    let nodes = [];
    let timer = 0;
    do {
        await sleep(5000);
        nodes = document.querySelectorAll(".d-grid.gap-3 a");
        if (++timer > 10) {
            document.title = "失败";
            return;
        }
    }
    while (nodes.length == 0);

    let arr = [...nodes];
    arr.pop();
    arr = arr.map(i => {
        console.log(i.innerText)
        console.log(i.href)
        let t = i.innerText.match(/(\d+)x\d+/);
        return {
            num: Number(t[1]),
            size: t[0],
            url: i.href

        }
    })
    arr.sort((a, b) => b.num - a.num);
    console.log(arr);
    document.title = "完成";
    let link = arr[0].url;
    post({
        video: link,
        src: url,
        size: arr[0].size
    });
}

function sleep(n) {
    return new Promise(resolve => {
        setTimeout(resolve, n);
    })
}

function post(param) {
    console.log(param)
    fetch(URL, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(param)
    })
        .then(response => response.json())
        .then(res => {
            console.log("res download", res)

            if (res.tip) {
                msg(res.tip);
            } else {
                msg("保存失败");
            }
        })
        .catch(error => {
            msg("保存错误");
        });
}

function msg(str) {
    console.log(str);
}

// Jsz.04005301!
// 49.51.69.50